import React, { useEffect, useRef, useState } from "react";
import { Box } from "$components";
import "./style.less";
import { useSelector, useDispatch } from "react-redux";
import { getTypeDistribution } from "../actions/bigscreen";

const IPChart = () => {
  const dispatch = useDispatch();
  const [ipTypeData, setIpTypeData] = useState([]);
  const canvasRef = useRef(null);
  const [totalCount, setTotalCount] = useState(0);
  const [selectedType, setSelectedType] = useState(null);
  const [highlightedIndex, setHighlightedIndex] = useState(null);
  const [animProgress, setAnimProgress] = useState(0);
  const animRef = useRef(null);

  // 圆环配置
  const ringConfig = {
    lineWidth: 10,
    highlightWidth: 12,
    spacing: 28,  // 关键：减小间距
    dotSize: 7,
    highlightDotSize: 9
  };

  // 颜色映射 - 确保所有类型都有正确的映射
  const typeColorMap = {
    "PCT": {
      color: "linear-gradient(to top,#FFE8E8E8 0%,#00E4E4E4 100%)",
      gradientColors: ["#FFE8E8E8", "#00E4E4E4"],
      startAngleOffset: 0, // 0度
    },
    "实用新型": {
      color: "linear-gradient(to top, #09D5FF 0%, #09d5ff00 100%)",
      gradientColors: ["#09D5FF", "#09d5ff00"],
      startAngleOffset: Math.PI * 1.2, // 约216度
    },
    "发明专利": {
      color: "linear-gradient(to top,#82E897,#004BCC5E)",
      gradientColors: ["#82E897", "#004BCC5E"],
      startAngleOffset: Math.PI * 0.6, // 约108度
    },
    "软件著作权": {
      color: "linear-gradient(to top,rgba(241, 238, 116, 0),#F1EE74) ",
      gradientColors: ["#F1EE74", "rgba(241, 238, 116, 0)"],
      startAngleOffset: Math.PI * 1.5, // 约270度
    },
    "外观专利": {
      color: "linear-gradient(to top,rgba(67, 97, 238, 0),#4361EE)",
      gradientColors: ["#4361EE", "rgba(67, 97, 238, 0)"],
      startAngleOffset: Math.PI * 0.9, // 约162度
    },
    "商标": {
      color: "linear-gradient(to top,rgba(241, 158, 116, 0),#F19A74)",
      gradientColors: ["#F19A74", "rgba(241, 158, 116, 0)"],
      startAngleOffset: Math.PI * 0.3, // 约54度
    },
  };

  // 获取数据
  useEffect(() => {
    dispatch(getTypeDistribution()).then((res) => {
      if (res.payload && res.payload.data) {
        // 处理数据，添加颜色信息
        const formattedData = res.payload.data.typeDistribution.map(item => {
          // 查找匹配的颜色映射，确保大小写和空格不影响匹配
          const matchKey = Object.keys(typeColorMap).find(
            key => key.toLowerCase().replace(/\s+/g, '') === item.type.toLowerCase().replace(/\s+/g, '')
          );
          
          const colorInfo = matchKey ? typeColorMap[matchKey] : {
            color: "linear-gradient(to top,rgba(180, 180, 180, 0),#AAAAAA)",
            gradientColors: ["#AAAAAA", "rgba(180, 180, 180, 0)"],
            startAngleOffset: 0
          };
          
          return {
            ...item,
            ...colorInfo
          };
        });
        
        // 打印数据以便调试
        console.log("Formatted data:", formattedData);
        
        setIpTypeData(formattedData);
        setTotalCount(res.payload.data.totalCount);

    // 启动动画
    startAnimation();
      }
    });

    return () => {
      if (animRef.current) {
        cancelAnimationFrame(animRef.current);
      }
    };
  }, []);

  // 动画效果
  const startAnimation = () => {
    let startTime;
    const duration = 1500; // 动画持续时间（毫秒）

    const animate = (timestamp) => {
      if (!startTime) startTime = timestamp;
      const elapsed = timestamp - startTime;
      const progress = Math.min(elapsed / duration, 1);

      setAnimProgress(progress);

      if (progress < 1) {
        animRef.current = requestAnimationFrame(animate);
      }
    };

    animRef.current = requestAnimationFrame(animate);
  };

  // 绘制图表
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || ipTypeData.length === 0) return;

    const ctx = canvas.getContext("2d");
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = Math.min(centerX, centerY) - 20; // 减小边距，增大整体圆环

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制背景圆环
    drawBackgroundCircles(ctx, centerX, centerY, radius);

    // 绘制数据圆环
    drawDataArcs(ctx, centerX, centerY, radius, ipTypeData, totalCount);
    
    // 绘制中心百分比
    if (highlightedIndex !== null && ipTypeData[highlightedIndex]) {
      drawCenterPercentage(ctx, centerX, centerY, ipTypeData[highlightedIndex]);
    }
  }, [ipTypeData, selectedType, totalCount, highlightedIndex, animProgress]);

  // 绘制中心百分比
  const drawCenterPercentage = (ctx, centerX, centerY, item) => {
    if (!item || typeof item.percentage === 'undefined') {
      console.warn("Invalid item or missing percentage:", item);
      return;
    }
    
    // 创建圆形背景
    ctx.beginPath();
    ctx.arc(centerX, centerY, 60, 0, 2 * Math.PI);
    
    // 渐变背景
    const bgGradient = ctx.createRadialGradient(
      centerX, 
      centerY, 
      0, 
      centerX, 
      centerY, 
      60
    );
    bgGradient.addColorStop(0, "rgba(10, 30, 50, 0.8)");
    bgGradient.addColorStop(1, "rgba(5, 15, 25, 0.9)");
    ctx.fillStyle = bgGradient;
    ctx.fill();
    
    // 确保有有效的渐变颜色
    const borderColor = item.gradientColors && item.gradientColors[0] 
      ? item.gradientColors[0] 
      : "#FFFFFF";
    
    // 绘制边框
    ctx.strokeStyle = borderColor;
    ctx.lineWidth = 2;
    ctx.stroke();
    
    // 绘制百分比文本
    ctx.font = "bold 24px Arial";
    ctx.fillStyle = borderColor;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText(`${item.percentage}%`, centerX, centerY - 5);
    
    // 绘制类型名称
    ctx.font = "12px Arial";
    ctx.fillStyle = "#ffffff";
    ctx.fillText(item.type, centerX, centerY + 20);
    
    // 调试信息
    console.log("Drawing center percentage for:", item.type, item.percentage);
  };

  // 计算圆环的显示长度（视觉上更好看，而不是严格按比例）
  const calculateArcLength = (count, total, index) => {
    // 找出最大值
    const maxCount = Math.max(...ipTypeData.map((item) => item.count));

    // 基础长度：保证每个圆环至少有一定长度
    const baseLength = 0.3;

    // 根据count相对于最大值的比例计算额外长度
    const extraLength = 0.6 * (count / maxCount);

    // 总长度 = 基础长度 + 额外长度，乘以动画进度
    return (baseLength + extraLength) * animProgress;
  };

  // 绘制背景圆环
  const drawBackgroundCircles = (ctx, centerX, centerY, radius) => {
    // 计算可以绘制的最大圆环数量，确保最内层圆环半径不会小于20px
    const maxRings = Math.min(
      ipTypeData.length,
      Math.floor((radius - 20) / ringConfig.spacing) + 1
    );

    // 绘制完整的灰色渐变背景圆环
    for (let i = 0; i < maxRings; i++) {
      const arcRadius = radius - i * ringConfig.spacing;

      // 确保半径为正值
      if (arcRadius <= 0) continue;

      // 创建灰色渐变背景
      ctx.beginPath();
      ctx.arc(centerX, centerY, arcRadius, 0, 2 * Math.PI);

      // 创建径向渐变
      const bgGradient = ctx.createRadialGradient(
        centerX,
        centerY,
        0,
        centerX,
        centerY,
        radius
      );
      bgGradient.addColorStop(0, "rgba(20, 60, 100, 0.1)");
      bgGradient.addColorStop(1, "rgba(10, 30, 50, 0.3)");

      ctx.strokeStyle = "rgba(40, 80, 120, 0.2)";
      ctx.lineWidth = ringConfig.lineWidth;
      ctx.stroke();

      // 添加细线轮廓
      ctx.beginPath();
      ctx.arc(centerX, centerY, arcRadius, 0, 2 * Math.PI);
      ctx.strokeStyle = "rgba(60, 120, 180, 0.15)";
      ctx.lineWidth = 1;
      ctx.stroke();
    }

    // 绘制中心圆轮廓（不填充）
    ctx.beginPath();
    ctx.arc(centerX, centerY, 60, 0, 2 * Math.PI);
    ctx.strokeStyle = "rgba(0, 150, 255, 0.5)";
    ctx.lineWidth = 1;
    ctx.stroke();
  };

  // 绘制数据圆弧
  const drawDataArcs = (ctx, centerX, centerY, radius, data, total) => {
    // 计算可以绘制的最大圆环数量
    const maxRings = Math.min(
      data.length,
      Math.floor((radius - 20) / ringConfig.spacing) + 1
    );

    // 只绘制能够容纳的圆环数量
    data.slice(0, maxRings).forEach((item, index) => {
      const arcRadius = radius - index * ringConfig.spacing;

      // 确保半径为正值
      if (arcRadius <= 0) return;

      // 使用视觉上更好看的圆弧长度
      const arcLength = calculateArcLength(item.count, total, index);

      // 确保圆弧长度有效
      if (arcLength <= 0) return;

      // 使用不同的起始角度，形成错落感
      const startAngle = -Math.PI / 2 + (item.startAngleOffset || 0); // 从顶部开始，加上偏移
      const endAngle = startAngle - 2 * Math.PI * arcLength; // 负号使其逆时针

      // 绘制圆弧（逆时针方向）
      ctx.beginPath();
      ctx.arc(centerX, centerY, arcRadius, startAngle, endAngle, true); // true表示逆时针

      try {
        // 安全地创建渐变色 - 从上到右渐变（从浅到深）
        const topX = centerX + arcRadius * Math.cos(startAngle);
        const topY = centerY + arcRadius * Math.sin(startAngle);
        const rightX = centerX + arcRadius * Math.cos(endAngle);
        const rightY = centerY + arcRadius * Math.sin(endAngle);

        // 确保坐标是有限数值
        if (
          !isFinite(topX) ||
          !isFinite(topY) ||
          !isFinite(rightX) ||
          !isFinite(rightY)
        ) {
          ctx.strokeStyle = item.color;
        } else {
          // 创建从起点到终点的渐变色
          const gradient = ctx.createLinearGradient(topX, topY, rightX, rightY);

          if (item.specialGradient && item.gradientStops) {
            // 使用特殊的多点渐变
            item.gradientStops.forEach((stop) => {
              gradient.addColorStop(stop.offset, stop.color);
            });
          } else {
            // 使用普通的双色渐变
            gradient.addColorStop(0, item.gradientColors[0]);
            gradient.addColorStop(1, item.gradientColors[1]);
          }

          ctx.strokeStyle = gradient;
        }
      } catch (error) {
        // 如果渐变创建失败，使用纯色
        ctx.strokeStyle = item.color;
      }

      ctx.lineWidth =
        highlightedIndex === index
          ? ringConfig.highlightWidth
          : ringConfig.lineWidth;
      ctx.lineCap = "round";
      ctx.stroke();

      // 只有在动画完成后才显示小圆点和标签
      if (animProgress >= 0.99) {
        // 在圆弧末端添加一个小圆点
        const dotX = centerX + arcRadius * Math.cos(endAngle);
        const dotY = centerY + arcRadius * Math.sin(endAngle);

        ctx.beginPath();
        ctx.arc(
          dotX,
          dotY,
          highlightedIndex === index
            ? ringConfig.highlightDotSize
            : ringConfig.dotSize,
          0,
          2 * Math.PI
        );

        try {
          // 创建径向渐变
          const dotGradient = ctx.createRadialGradient(
            dotX,
            dotY,
            0,
            dotX,
            dotY,
            highlightedIndex === index
              ? ringConfig.highlightDotSize
              : ringConfig.dotSize
          );
          dotGradient.addColorStop(0, "#ffffff");
          dotGradient.addColorStop(1, item.color);
          ctx.fillStyle = dotGradient;
        } catch (error) {
          // 如果渐变创建失败，使用纯色
          ctx.fillStyle = "#ffffff";
        }

        ctx.fill();

        // 如果是被选中的类型，在末端添加数值标签
        if (selectedType && selectedType.type === item.type) {
          ctx.font = "bold 16px Arial";
          ctx.fillStyle = "#ffffff";
          ctx.textAlign = "center";
          ctx.textBaseline = "middle";

          // 计算文本位置
          const textDistance = arcRadius + 25;
          const textX = centerX + textDistance * Math.cos(endAngle);
          const textY = centerY + textDistance * Math.sin(endAngle);

          // 绘制数值标签背景
          ctx.beginPath();
          ctx.arc(textX, textY, 18, 0, 2 * Math.PI);

          try {
            const labelGradient = ctx.createRadialGradient(
              textX,
              textY,
              0,
              textX,
              textY,
              18
            );
            labelGradient.addColorStop(0, "rgba(0, 50, 100, 0.8)");
            labelGradient.addColorStop(1, "rgba(0, 30, 60, 0.7)");
            ctx.fillStyle = labelGradient;
          } catch (error) {
            // 如果渐变创建失败，使用纯色
            ctx.fillStyle = "rgba(0, 30, 60, 0.7)";
          }

          ctx.fill();

          ctx.fillStyle = item.color;
          ctx.fillText(item.count, textX, textY);
        }
      }
    });
  };

  // 处理鼠标悬停
  const handleHoverItem = (index) => {
    console.log("Hovering item:", ipTypeData[index]?.type);
    setHighlightedIndex(index);
  };

  return (
    <Box title="知识产权占比">
      <div className="ip-chart-container">
        <canvas
          ref={canvasRef}
          width={380}
          height={380}
          className="ip-chart-canvas"
        />
          </div>
      <div className="ip-chart-text">
        {ipTypeData.map((item, index) => (
          <div 
            className="ip-chart-text-item" 
            key={item.type}
            onMouseEnter={() => handleHoverItem(index)}
            onMouseLeave={() => setHighlightedIndex(null)}
          >
            <div
              className="ip-chart-text-item-color"
              style={{ background: item.color }}
            ></div>
            <div className="ip-chart-text-item-title">{item.type}</div>
            <div className="ip-chart-text-item-value">{item.count}件</div>
          </div>
        ))}
      </div>
    </Box>
  );
};

export default IPChart; 
